<template>
  <div>
    <!-- 头部 -->
    <nav-header></nav-header>
    <!-- 头部 -->

    <!-- 面包屑 -->
    <nav-bread>
      <span>My Address</span>
    </nav-bread>
    <!-- 面包屑 -->
    <div class="checkout-page">
      <svg
        style="position: absolute; width: 0; height: 0; overflow: hidden;"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink"
      >
        <defs>
          <symbol id="icon-add" viewBox="0 0 31 32">
            <title>add</title>
            <path
              class="path1"
              d="M30.745 15.152h-14.382v-14.596c0-0.308-0.243-0.557-0.543-0.557s-0.543 0.249-0.543 0.557v14.596h-14.665c-0.3 0-0.543 0.249-0.543 0.557s0.243 0.557 0.543 0.557h14.665v15.177c0 0.307 0.243 0.557 0.543 0.557s0.543-0.249 0.543-0.557v-15.177h14.382c0.3 0 0.543-0.249 0.543-0.557s-0.243-0.557-0.543-0.557z"
            ></path>
          </symbol>
          <symbol id="icon-ok" viewBox="0 0 32 32">
            <title>ok</title>
            <path
              class="path1"
              d="M14.084 20.656l-7.845-9.282c-1.288-1.482-3.534-1.639-5.016-0.351s-1.639 3.534-0.351 5.016l10.697 12.306c1.451 1.669 4.057 1.623 5.448-0.096l18.168-22.456c1.235-1.527 0.999-3.765-0.528-5.001s-3.765-0.999-5.001 0.528l-15.573 19.337z"
            ></path>
          </symbol>
          <symbol id="icon-edit" viewBox="0 0 32 32">
            <title>edit</title>
            <path
              class="path1"
              d="M28.287 8.51l-4.805-4.806 0.831-0.831c0.472-0.472 1.086-0.777 1.564-0.777 0.248 0 0.452 0.082 0.622 0.253l3.143 3.144c0.539 0.54 0.133 1.529-0.524 2.186l-0.831 0.831zM26.805 9.992l-1.138 1.138-4.805-4.806 1.138-1.138 4.805 4.806zM24.186 12.612l-14.758 14.762-4.805-4.806 14.758-14.762 4.805 4.806zM7.379 28.288l-4.892 1.224 1.223-4.894 3.669 3.67zM31.123 4.011l-3.143-3.144c-0.567-0.567-1.294-0.867-2.103-0.867-1.036 0-2.174 0.52-3.045 1.391l-20.429 20.436c-0.135 0.134-0.23 0.302-0.276 0.487l-2.095 8.385c-0.089 0.355 0.017 0.736 0.276 0.995 0.198 0.198 0.461 0.307 0.741 0.307 0.085 0 0.171-0.010 0.254-0.031l8.381-2.096c0.185-0.047 0.354-0.142 0.487-0.276l20.43-20.436c1.409-1.41 2.042-3.632 0.524-5.15v0z"
            ></path>
          </symbol>
          <symbol id="icon-del" viewBox="0 0 32 32">
            <title>delete</title>
            <path
              class="path1"
              d="M11.355 4.129v-2.065h9.29v2.065h-9.29zM6.194 29.935v-23.742h19.613v23.742h-19.613zM30.968 4.129h-8.258v-3.097c0-0.569-0.463-1.032-1.032-1.032h-11.355c-0.569 0-1.032 0.463-1.032 1.032v3.097h-8.258c-0.569 0-1.032 0.463-1.032 1.032s0.463 1.032 1.032 1.032h3.097v24.774c0 0.569 0.463 1.032 1.032 1.032h21.677c0.569 0 1.032-0.463 1.032-1.032v-24.774h3.097c0.569 0 1.032-0.463 1.032-1.032s-0.463-1.032-1.032-1.032v0z"
            ></path>
            <path
              class="path2"
              d="M10.323 9.806c-0.569 0-1.032 0.463-1.032 1.032v14.452c0 0.569 0.463 1.032 1.032 1.032s1.032-0.463 1.032-1.032v-14.452c0-0.569-0.463-1.032-1.032-1.032z"
            ></path>
            <path
              class="path3"
              d="M16 9.806c-0.569 0-1.032 0.463-1.032 1.032v14.452c0 0.569 0.463 1.032 1.032 1.032s1.032-0.463 1.032-1.032v-14.452c0-0.569-0.463-1.032-1.032-1.032z"
            ></path>
            <path
              class="path4"
              d="M21.677 9.806c-0.569 0-1.032 0.463-1.032 1.032v14.452c0 0.569 0.463 1.032 1.032 1.032s1.032-0.463 1.032-1.032v-14.452c0-0.569-0.463-1.032-1.032-1.032z"
            ></path>
          </symbol>
          <symbol id="icon-clock" viewBox="0 0 32 32">
            <title>clock</title>
            <path
              class="path1"
              d="M29.333 16c0-7.364-5.97-13.333-13.333-13.333s-13.333 5.97-13.333 13.333c0 7.364 5.97 13.333 13.333 13.333s13.333-5.97 13.333-13.333v0 0 0 0 0 0zM0 16c0-8.837 7.163-16 16-16s16 7.163 16 16c0 8.837-7.163 16-16 16s-16-7.163-16-16zM14.667 14.667v1.333h2.667v-10.667h-2.667v9.333zM24 18.667h1.333v-2.667h-10.667v2.667h9.333z"
            ></path>
          </symbol>
          <symbol id="icon-question" viewBox="0 0 32 32">
            <title>question</title>
            <path
              class="path1"
              d="M16 2.56c7.411 0 13.44 6.029 13.44 13.44s-6.029 13.44-13.44 13.44c-7.411 0-13.44-6.029-13.44-13.44s6.029-13.44 13.44-13.44zM16 0c-8.822 0-16 7.178-16 16s7.178 16 16 16c8.822 0 16-7.178 16-16s-7.178-16-16-16z"
            ></path>
            <path
              class="path2"
              d="M16 22.080c-1.059 0-1.92 0.861-1.92 1.92s0.861 1.92 1.92 1.92c1.059 0 1.92-0.861 1.92-1.92s-0.861-1.92-1.92-1.92z"
            ></path>
            <path
              class="path3"
              d="M12.16 12.48c0.706 0 1.28-0.574 1.28-1.28 0-1.412 1.148-2.56 2.56-2.56s2.56 1.148 2.56 2.56c0 1.412-1.148 2.56-2.56 2.56-0.706 0-1.28 0.574-1.28 1.28v3.84c0 0.706 0.574 1.28 1.28 1.28s1.28-0.574 1.28-1.28v-2.723c2.224-0.575 3.84-2.616 3.84-4.957 0-2.823-2.297-5.12-5.12-5.12s-5.12 2.297-5.12 5.12c0 0.706 0.574 1.28 1.28 1.28z"
            ></path>
          </symbol>
        </defs>
      </svg>
      <div class="container">
        <div class="checkout-addr">
          <div class="page-title-normal">
            <h2 class="page-title-h2"><span>check out</span></h2>
          </div>
          <!-- process step -->
          <div class="check-step">
            <ul>
              <li class="cur"><span>Confirm</span> address</li>
              <li><span>View your</span> order</li>
              <li><span>Make</span> payment</li>
              <li><span>Order</span> confirmation</li>
            </ul>
          </div>

          <!-- address list -->
          <div class="page-title-normal checkout-title">
            <h2><span>Shipping address</span></h2>
          </div>
          <div class="addr-list-wrap">
            <div class="addr-list">
              <ul>
                <li
                  v-for="(item, index) in addressListFilter"
                  :key="item.addressId"
                  :class="{ check: current == index, checked: item.isDefault }"
                  @click="currentCheck(index, item.addressId)"
                >
                  <dl>
                    <dt>{{ item.userName }}</dt>
                    <dd class="address">{{ item.streetName }}</dd>
                    <dd class="tel">{{ item.tel }}</dd>
                  </dl>
                  <div class="addr-opration addr-del">
                    <a
                      href="javascript:;"
                      class="addr-del-btn"
                      @click="removeAddress(item.addressId)"
                    >
                      <svg class="icon icon-del">
                        <use xlink:href="#icon-del"></use>
                      </svg>
                    </a>
                  </div>
                  <div class="addr-opration addr-set-default">
                    <a
                      href="javascript:;"
                      class="addr-set-default-btn"
                      v-if="!item.isDefault"
                      @click="setDefault(item.addressId)"
                      ><i>Set default</i></a
                    >
                  </div>
                  <div class="addr-opration addr-default" v-if="item.isDefault">
                    Default address
                  </div>
                </li>
                <li class="addr-new" @click="addNewAddress">
                  <div class="add-new-inner">
                    <i class="icon-add">
                      <svg class="icon icon-add">
                        <use xlink:href="#icon-add"></use>
                      </svg>
                    </i>
                    <p>Add new address</p>
                  </div>
                </li>
              </ul>
            </div>

            <div class="shipping-addr-more">
              <a
                class="addr-more-btn up-down-btn"
                href="javascript:;"
                @click="expand"
                :class="{ open: limit > 3 }"
              >
                {{ expandText }}
                <i class="i-up-down">
                  <i class="i-up-down-l"></i>
                  <i class="i-up-down-r"></i>
                </i>
              </a>
            </div>
          </div>

          <!-- shipping method-->
          <div class="page-title-normal checkout-title">
            <h2><span>Shipping method</span></h2>
          </div>
          <div class="shipping-method-wrap">
            <div class="shipping-method">
              <ul>
                <li class="check">
                  <div class="name">Standard shipping</div>
                  <div class="price">Free</div>
                  <div class="shipping-tips">
                    <p>
                      Once shipped，Order should arrive in the destination in
                      1-7 business days
                    </p>
                  </div>
                </li>
              </ul>
            </div>
          </div>

          <div class="order-foot-wrap">
            <div class="prev-btn-wrap">
              <a class="btn btn--m" @click="goback">Previous</a>
            </div>
            <div class="next-btn-wrap">
              <a class="btn btn--m btn--red" href="javascript:;" @click="next"
                >Next</a
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部区域 -->
    <nav-footer></nav-footer>
    <!-- 底部区域 -->

    <!-- 添加地址弹框 -->
    <el-dialog
      title="添加新地址"
      :visible.sync="addNewAddressDialog"
      width="500px"
      @close="closeaddNewAddressDialog"
    >
      <el-form
        :model="addNewForm"
        :rules="addNewFormRules"
        ref="addNewFormRef"
        label-width="100px"
        status-icon
      >
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="addNewForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="省市区/县" prop="address1">
          <el-cascader
            expand-trigger="hover"
            v-model="addNewForm.address1"
            :options="addressData"
            style="width:100%"
            filterable
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address2">
          <el-input v-model="addNewForm.address2"></el-input>
        </el-form-item>
        <el-form-item label="邮政编码" prop="postCode">
          <el-input v-model="addNewForm.postCode" type="Number"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="tel">
          <el-input v-model="addNewForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addNewAddressDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAddNew">添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style></style>
<script>
import NavHeader from '../components/NavHeader'
import NavFooter from '../components/NavFooter'
import NavBread from '../components/NavBread'
import addressData from '../util/citydata'
import qs from 'qs'
export default {
  data() {
    //校验手机号码
    var checkMobile = (rule, value, cb) => {
      const phoneRule = /^(1[3|7][0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/

      if (phoneRule.test(value)) {
        //合法手机号码
        return cb()
      }
      cb(new Error('手机号码格式有误！'))
    }
    return {
      //用户id
      userId: '',
      //地址列表
      addressList: [],
      //控制地址显示的个数
      limit: 3,
      //展开地址的文字控制
      expandText: 'show more',
      //控制地址的高亮显示
      current: 0,
      //控制添加地址弹框的显示与隐藏
      addNewAddressDialog: false,
      //添加新地址表单对象
      addNewForm: {
        addressId: '',
        userName: '',
        address1: [],
        address2: '',
        postCode: '',
        tel: ''
      },
      //省级联动数据
      addressData,
      //添加新地址的校验对象
      addNewFormRules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 16, message: '姓名长度为2~16', trigger: 'blur' }
        ],
        address1: [
          { required: true, message: '请选择省市区', trigger: 'blur' }
        ],
        address2: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        postCode: [
          { required: true, message: '请输入邮政编码', trigger: 'blur' },
          { min: 6, max: 6, message: '邮政编码长度为6位', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //保存默认地址的id以便发货
      addressId: ''
    }
  },
  mounted() {
    //获取地址列表
    this.getAddress()
    this.current = this.addressList.findIndex(item => item.isDefault)
  },
  methods: {
    //获取地址列表
    getAddress() {
      this.userId = this.$cookies.get('userId')
      this.$axios
        .get('/address/getAddress', {
          params: {
            userId: this.userId
          }
        })
        .then(res => {
          // console.log(res)
          this.addressList = res.data.addressList
          this.addressList.forEach(item => {
            if (item.isDefault) {
              //默认地址
              this.addressId = item.addressId
              console.log(this.addressId)
            }
          })
        })
        .catch(err => console.log(err))
    },
    //删除地址
    removeAddress(addressId) {
      //如果只剩一个地址，不允许删除
      if (this.countAddressNum == 1) {
        this.$alert('地址列只剩一条数据，已无法继续删除。', '提示', {
          confirmButtonText: '好的'
        }).then(() => this.$message.info('没有地址没办法给您发货呢!!!'))
        //阻止程序向下执行
        return
      }
      //根据用户id和地址id发送axios请求
      this.$confirm('您确定要删除该地址吗?', '删除提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      })
        .then(() => {
          this.$axios
            .post(
              '/address/removeAddress',
              qs.stringify({ userId: this.userId, addressId })
            )
            .then(res => {
              // console.log(res)
              if (res.status != 200) return this.$message.error(res.msg)
              //删除成功
              this.$message.success(res.msg)
              //重新获取地址列表
              this.getAddress()
            })
            .catch(err => console.log(err))
        })
        .catch(() => this.$message.info('删除操作已取消!'))
    },
    //点击more展开所有地址
    expand() {
      if (this.limit == 3) {
        //让limit等于地址数组的长度
        this.limit = this.addressList.length
        this.expandText = this.limit > 3 ? 'hidden' : 'no more'
      } else {
        this.limit = 3
        this.expandText = 'show more'
      }
    },
    //切换地址高亮
    currentCheck(index, addressId) {
      this.current = index
      this.addressId = addressId
      console.log(this.addressId)
    },
    //设置默认地址
    setDefault(addressId) {
      // console.log(addressId)
      this.$axios
        .post(
          '/address/setDefault',
          qs.stringify({ userId: this.userId, addressId })
        )
        .then(res => {
          if (res.status != 200) return this.$message.error('设置失败')
          this.$message.success(res.msg)
          //重新获取地址列表
          this.getAddress()
        })
        .catch(err => console.log(err))
    },
    //点击添加新地址触发
    addNewAddress() {
      //显示弹框
      this.addNewAddressDialog = true
    },
    //监听添加新地址弹框的关闭事件
    closeaddNewAddressDialog() {
      this.$refs.addNewFormRef.resetFields()
    },
    //点击确定按钮添加新地址
    submitAddNew() {
      this.addNewForm.streetName =
        this.addNewForm.address1.join('') + this.addNewForm.address2
      this.addNewForm.userId = this.userId
      // console.log(this.addNewForm)
      //预校验表单
      this.$refs.addNewFormRef.validate(valid => {
        if (valid) {
          //校验成功
          this.$axios
            .post('/address/addNewAddress', qs.stringify(this.addNewForm))
            .then(res => {
              console.log(res)
              if (res.status != 200) return this.$message.error('添加失败')
              //添加成功
              this.$message.success(res.msg)
              //隐藏弹框
              this.addNewAddressDialog = false
              //重新获取地址列表
              this.getAddress()
            })
            .catch(err => console.log(err))
        }
      })
    },
    //点击next触发
    next() {
      //判断用户是否选中了地址
      if (!this.addressId) {
        //没选中地址
        this.$message.error('请选择配送地址!!!')
        return
      }
      const userName = this.$cookies.get('userName')
      //判断登陆状态
      if (this.userId && userName) {
        this.$router.push('/orderConfirm?addressId=' + this.addressId)
        this.$message.success('请确认订单信息')
      } else {
        //未登录
        this.$message.error('操作失败，请判断登陆状态')
        this.$router.push('/goodList').catch(err => err)
      }
    },
    //回退
    goback() {
      this.$router.go(-1)
    }
  },
  computed: {
    addressListFilter() {
      //利用slice截取三条地址，返回值是一个全新数组，不会修改原数组
      return this.addressList.slice(0, this.limit)
    },
    countAddressNum() {
      return this.addressList.length
    }
  },
  components: {
    NavHeader,
    NavFooter,
    NavBread
  }
}
</script>
